/*
 *  Copyright 2011-2012 Redia A/S
 * 
 *  This file is part of Redias Android Utilities.
 *
 *  Redias Android Utilities is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  Redias Android Utilities is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *  
 *  You should have received a copy of the GNU General Public License
 *  along with Redias Android Utilities.  If not, see <http://www.gnu.org/licenses/>.
 */
package dk.redia.lib.utils;

import java.net.URLEncoder;
import java.util.HashSet;
import java.util.Set;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;

import dk.redia.lib.config.RediaConfig;
import dk.redia.lib.log.Log;

public class FogbugzErrorReporter {
	
	private static Set<ErrorReport> pendingReports;
	private static String logTag = "FogbugzErrorReporter";
	
	static {
		pendingReports = new HashSet<ErrorReport>();
	}
	
	public static void report(ErrorReport e) {
		report(e, false, false);
	}
	
	public static void report(ErrorReport e, boolean forceNewBug, boolean friendlyResponse) {
		
		pendingReports.add(e);
		
		Set<ErrorReport> pendingReportsCp = new HashSet<ErrorReport>(pendingReports);
		
		for (ErrorReport r : pendingReportsCp) {
			if (sendReport(e, forceNewBug, friendlyResponse)) {
				pendingReports.remove(r);
				Log.d(logTag, "Successfully transmitted fogbugz error report");
			} else {
				Log.w(logTag, "Failed to report error to fogbugz. Will retry later.");
			}
		}		
	}
	
	
	private static boolean sendReport(ErrorReport e, boolean forceNewBug, boolean friendlyResponse) {
		DefaultHttpClient client = new DefaultHttpClient();
		StringBuilder baseUrl = new StringBuilder(RediaConfig.getFogbugzScoutSubmitUrl());
		baseUrl.append("ScoutUserName=");
		baseUrl.append(URLEncoder.encode("Remote Error Reports"));
	    baseUrl.append("&");

	    baseUrl.append("ScoutProject=automatederrorreports");
	    baseUrl.append("&");

	    baseUrl.append("ScoutArea=Misc");
	    baseUrl.append("&");

	    baseUrl.append("Description=");
	    baseUrl.append(URLEncoder.encode(e.getDescription()));
	    if (e.getException()!=null) {
	    	StackTraceElement topElement = e.getException().getStackTrace()[0];
	    	String position = topElement.getFileName() + ":" + topElement.getLineNumber();
	    	baseUrl.append(URLEncoder.encode(" " + position));
	    }
	    baseUrl.append("&");

	    baseUrl.append("ForceNewBug=");
	    baseUrl.append(forceNewBug ? 1 : 0);
	    baseUrl.append("&");

	    baseUrl.append("Extra=");
	    baseUrl.append(URLEncoder.encode(e.getExtra() + "\n"));
	    baseUrl.append(URLEncoder.encode("Stack trace: \n"));
	    if (e.getException()!=null) {
	    	baseUrl.append(URLEncoder.encode(e.getException().getMessage() + "\n"));
			for (StackTraceElement element : e.getException().getStackTrace() ){
			    baseUrl.append(URLEncoder.encode(element.toString() + "\n"));
			}
	    }
	    baseUrl.append("&");

	    baseUrl.append("Email=");
	    baseUrl.append(e.getEmail());
	    baseUrl.append("&");

	    baseUrl.append("ScoutDefaultMessage=");
	    baseUrl.append(e.getDefaultMessage());
	    baseUrl.append("&");

	    baseUrl.append("FriendlyResponse=");
	    baseUrl.append(friendlyResponse ? 1 : 0);
		HttpUriRequest request = new HttpGet(baseUrl.toString());
		try {
			HttpResponse r = client.execute(request);
			Log.d(logTag, "Fogbugz reported status: " + r.getStatusLine());
			return true;
		} catch (Exception e1) {
			Log.w(logTag, "Error during error reporting: " + e1.getMessage());
			return false;
		}
	}

	
}
